import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-project-car',
	templateUrl: './project-car.component.html',
})
export class ProjectCarComponent implements OnInit {
	validatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			// installFactory: {
			// 	trigger:"change",
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请选择安装厂区'
			// 		}
			// 	}
			// },
			carNumberInput: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择车牌号码'
					}
				}
			},
			dockingFactory: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择对接厂区'
					}
				}
			},
			dockingTime: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择对接时间'
					}
				}
			},
			setupTime: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请输入提醒时间'
					}
				}
			},
		}
	}
	// 同步项目车辆的表单
	syncCarvalidatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			syncCompany: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择要同步项目车辆的公司'
					}
				}
			},
		}
	}
	// 取消服务到期提醒的公司的表单
	cancelDateCanpanyvalidatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			cancelCompany: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择要取消服务到期提醒的公司'
					}
				}
			},
		}
	}
	// 重置服务到期提醒的公司的表单
	resetDateCanpanyvalidatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			resetCompany: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择要重置服务提醒的公司'
					}
				}
			},
		}
	}
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	selectedCompanyName: string = ''; //公司名称
	selectedCompanyId: string = '';//公司ID
	selectedCompanyName2: string = ''; //公司名称
	selectedCompanyId2: string = '';//公司ID
	deviceId: string = ''; //公司名称
	carNumber: string = '';//公司ID
	type: string = '' //type  设备状态
  	useTypeL1: string = '' //useTypeL2  select值
  	useTypeL2: string = '' //useTypeL2  select值
	carTypeDetailList: any = [] //useTypeL2数据
	formType: string = 'new';
	status: string = '0';
	restDay: string = "";  // 剩余天数查询参数
	renewCount: string = "";  // 缴费次数参数
	remainingDay: number = 0; // 配置的剩余天数
	isShowDelete: any = false; //是否有删除权限
	companyParentList: any = []; //公司树的存储值
	// 查询参数
	dockingStatus: string = ""; // 停用启用状态
	dateType: string = "0"; // 时间区间的类型
	startTime: string = ''; // 开始时间
	endTime: string = '';  // 结束时间
	renewalDueTimeSort: string = '0'; //排序类型
	// 同步项目车辆的参数
	syncCompanyId: any = ""; // 选择的要同步的公司
	syncCompanyName: any = ""; // 选择的要同步的公司
	// 取消服务周期的公司
	cancelCompanyId: any = ""; // 取消服务周期的公司
	cancelCompanyName: any = ""; // 取消服务周期的公司名称
	companySeverRemind: any = '1'; // 取消服务类型
	// 重置服务到期时间的公司
	resetCompanyId: any = "";
	resetCompanyName: any = "";
	// 续费详情的表单数据
	renewDetailsTable: any = [];
	// 是否重置服务到期时间、续费次数
	isResetSelected: any = false;
	isEquals: any = ""; //厂区是否相同 0:否 1：是
	projectCarFrom: any = {
		id: '',
		deviceId: '',
		carNumber: '',
		installFactoryName: '',  //安装厂区
		installFactoryId: '',
		dockingFactoryName: '',  // 对接厂区
		dockingFactoryId: '',
		dockingTime: '',
		synRenew: '',
	}
	dockingRole: any = '' //对接角色
	RoleXxplain: any = '' //对接提示
	detailsFrom = {
		deviceId: '',
		carNumber: '',
		parentName: '',
		sim: '',
		loadCapacity: '',
		driverName: '',
		phone: '',
		carType: '',
		carAxleAmount: '',
		sensorAmount: '',
		companyName: '',
		sensorType: '',
		useTypeL1: '',
		useTypeL2: '',
		unit: '1',
		isShared: false,
		hwVersion: '',
		fwVersion: '',
		gpsId: '',
		userNameForCreate: '',
		gpsAntenna: '',
		gsmAntenna: '',
		gpsProblem: '',
		sensorProblem: '',
		inputDate: '',
		updateDate: '',
		picture: '',
		remark: '',
		isStatus: true,
		sensorChannel: []
	}
	setupTimeFrom = {
		setupTime: ''
	}
	carTypeList = carTypeListObj.carTypeList
	carUseList = carTypeListObj.carUseList
	carDeatailUseList = carTypeListObj.carDeatailUseList
	isSwitch: boolean = false; //默认隐藏

	businessTypeList: any[] = [] //行业类型
	businessType: string = ''

	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;

			// 从信息汇总跳转过来的数据
			const summaryInfoParams = JSON.parse(common.getCookie('jumpFromSummaryInfo'))
			if (summaryInfoParams) {
			  this.searchKey = summaryInfoParams.deviceId
			  this.isEquals = summaryInfoParams.isEquals
			  common.clearCookie('jumpFromSummaryInfo')
			}
		});
		this.businessTypeList = businessTypeList
	}
	// 接收子组件传递过来的数据
	getSelectTableTime(time) {
		this.startTime = time.startTime;
		this.endTime = time.endTime;
	}
	//安装厂区
	companySelected1(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	//对接厂区
	companySelected2(data) {
		this.selectedCompanyId2 = data.companyId;
		this.selectedCompanyName2 = data.companyName;
	}
	//父级公司树请求
	ngInitCompany() {
		this.jsonApiService.http("company/companytree.html", null).subscribe(data => {
			this.companyParentList = data;
		})
	}
	ngOnInit() {
		this.ngInitCompany();
		this.initBtn();
		System.import('assets/js/bootstrap-switch.min.js').then(
			() => {
				System.import('assets/css/bootstrap-switch.min.css').then(() => {
					this.load();
				})
			});


	}
	//table刷新
	refresh() {
		this.load();
	}
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_system:projectcar')));
		if (!btnData) {
			return
		};
		for (let item of btnData) {
			if (item.sourceKey === "system:projectcar:deleteBtn" && item.parentId) {
				this.isShowDelete = true;
			}

		}
	}

	//车辆用途change回调
	carUseTypeL1Change() {
		this.carTypeDetailList = []
		this.useTypeL2 = ''
		for (let item of this.carTypeList) {
		  if (item.id === this.useTypeL1) {
			this.carTypeDetailList = item.children
			break
		  }
		}
	  }

	//表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		var that = this;
		let timeCheck = common.correctTimeParams(that.startTime, this.endTime, 0);
		if (!timeCheck.status) {
			that.jsonApiService.message(timeCheck.message);
			return;
		}
		//当缴费次数有值的时候 对接厂区也必须有值存在
		if (that.renewCount.trim() && !this.selectedCompanyId2) {
			that.jsonApiService.message('请选择对接厂区');
			return
		}
		let data = {
			pageSize: that.pageSize,
			nowPage: that.curPage,
			parameters: {
				searchKey: that.searchKey,
				status: that.status,
				deviceId: that.deviceId,
				carNumber: that.carNumber,
				useTypeL1: this.useTypeL1,
        		useTypeL2: this.useTypeL2,
        		type: this.type,
				installFactoryId: that.selectedCompanyId,
				installFactoryName: that.selectedCompanyName,
				dockingFactoryId: that.selectedCompanyId2,
				dockingFactoryName: that.selectedCompanyName2,
				remaining: that.restDay.trim(),
				renewCount: that.renewCount.trim(),
				dockingStatus: this.dockingStatus, // 停用启用状态查询
				dateType: this.dateType,// 时间区间的类型
				startTime: this.startTime, // 开始时间
				endTime: this.endTime,  // 结束时间
				renewalDueTimeSort: this.renewalDueTimeSort, //排序类型
				isEquals: this.isEquals, //厂区是否相同
				businessType: this.businessType // 行业类型
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		that.jsonApiService.http("projectCar/list.html", reqdata).subscribe(data => {
			if (data.isSuccess) {
				// data.exhibitDatas[i].textTime = "已于" + data.exhibitDatas[i].renewalDueTime;
				// data.exhibitDatas[i].isShow = true
				// data.exhibitDatas[i].isExpire = true
				for (var i = 0; i < data.exhibitDatas.length; i++) {
					// 展示感叹号
					if (data.exhibitDatas[i].expire == 1) {
						data.exhibitDatas[i].textTime = "已于" + data.exhibitDatas[i].renewalDueTime;
						data.exhibitDatas[i].isShow = true
						data.exhibitDatas[i].isExpire = true
					} else if (data.exhibitDatas[i].expire == 3) {
						data.exhibitDatas[i].textTime = "将于" + data.exhibitDatas[i].renewalDueTime;
						data.exhibitDatas[i].isShow = true
						data.exhibitDatas[i].isExpire = false
					}
					// 停用启用
					if (data.exhibitDatas[i].status == 0) {
						data.exhibitDatas[i].isStatus = true;
					} else {
						data.exhibitDatas[i].isStatus = false
					}
					if (data.exhibitDatas[i].remainingDay.indexOf('-') != -1) {
						data.exhibitDatas[i].isSurplus = true
					} else {
						data.exhibitDatas[i].isSurplus = false
					}

					let remainingDay = data.exhibitDatas[i].remainingDay
					if (remainingDay.indexOf('-') != -1) {
						if (data.exhibitDatas[i].expire == '1' || data.exhibitDatas[i].expire == '0') {
							data.exhibitDatas[i].expireTime = '过期' + remainingDay.substring(1, remainingDay.length);
						} else if (data.exhibitDatas[i].expire == '2') {
							data.exhibitDatas[i].expireTime = '剩余' + remainingDay.substring(1, remainingDay.length);
						} else {
							data.exhibitDatas[i].expireTime = remainingDay
						}
					} else {
						if (data.exhibitDatas[i].expire == '1') {
							data.exhibitDatas[i].expireTime = '过期' + remainingDay;
						} else if (data.exhibitDatas[i].expire == '2' || data.exhibitDatas[i].expire == '0') {
							data.exhibitDatas[i].expireTime = '剩余' + remainingDay;
						} else {
							data.exhibitDatas[i].expireTime = remainingDay
						}
					}

				}



				System.import('assets/js/bootstrap-switch.min.js').then(
					() => {
						System.import('assets/css/bootstrap-switch.min.css').then(() => {
							setTimeout(function () {
								that.initSwitch();
								that.isSwitch = true
							}, 1)

						})
					});
				that.tips();
				that.tableData = data ? data.exhibitDatas : [];
				that.totalCount = data ? data.recordCount : 0;

			} else {
				that.jsonApiService.message(data.message);
			}
		})
		// 查询配置的剩余天数提醒天数
		that.jsonApiService.http("projectCar/getRemaining.html", reqdata).subscribe(data => {
			if (data.success) {
				that.remainingDay = data.data;
			}
		})
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				that.initCarNumbel();
			})
		});
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//编辑车辆
	updata_car(row, type, modal) {
		this.formType = type;
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					this.initDate();
				})
			}
		);
		if (type == 'role') {
			$('#projectCarModal').modal("show");
			this.userList = [];
		} else {
			modal.show();
		}
		$("#carNumberSelect2").select2({}).off(); //解绑
		this.initCar();
		$("#projectCarFrom").data('bootstrapValidator').resetForm();
		if (type == 'new') {
			this.projectCarFrom.installFactoryName = '';
			this.projectCarFrom.installFactoryId = '';
			this.projectCarFrom.dockingFactoryName = '';
			this.projectCarFrom.dockingFactoryId = '';
			this.projectCarFrom.deviceId = '';
			this.projectCarFrom.carNumber = '';
			this.dockingRole = '';  //对接角色
			this.userList = []; //对接角色数据清空
			this.projectCarFrom.id = '';
			this.isResetSelected = false;
			this.projectCarFrom.dockingTime = this.getNowFormatDate();
			$("#carNumberInput").val('');
			$('#carNumberSelect2').val("");
			$("#dockingTime").val(this.getNowFormatDate());
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title", "");
			$("#select2-carNumberSelect2-container").prepend(str);
		} else if (type == 'updata') {
			this.projectCarFrom.installFactoryName = row.installFactoryName
			this.projectCarFrom.installFactoryId = row.installFactoryId
			this.projectCarFrom.dockingFactoryName = row.dockingFactoryName
			this.projectCarFrom.dockingFactoryId = row.dockingFactoryId
			this.projectCarFrom.deviceId = row.deviceId
			this.projectCarFrom.carNumber = row.carNumber;
			this.projectCarFrom.id = row.id;
			this.projectCarFrom.dockingTime = row.dockingTime;
			this.isResetSelected = false;
		} else if (type == 'role') {
			for (var i = 0; i < this.tableData.length; i++) {
				if (this.tableData[i].id == row) {
					this.projectCarFrom.installFactoryName = this.tableData[i].installFactoryName
					this.projectCarFrom.installFactoryId = this.tableData[i].installFactoryId
					this.projectCarFrom.dockingFactoryName = this.tableData[i].dockingFactoryName
					this.projectCarFrom.dockingFactoryId = this.tableData[i].dockingFactoryId
					this.projectCarFrom.deviceId = this.tableData[i].deviceId
					this.projectCarFrom.carNumber = this.tableData[i].carNumber;
					this.projectCarFrom.id = this.tableData[i].id;
					this.projectCarFrom.dockingTime = this.tableData[i].dockingTime;
					this.isResetSelected = false;
					this.getRoleBycompanyConfig(this.projectCarFrom.dockingFactoryId);
				}
			}

		}
	}
	getNowFormatDate() {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		var strHours = date.getHours();
		var strMinutes = date.getMinutes();
		var strSeconds = date.getSeconds();

		var month_str
		if (month >= 1 && month <= 9) {
			month_str = "0" + month;
		} else {
			month_str = month;
		}
		var strDate_str
		if (strDate >= 0 && strDate <= 9) {
			strDate_str = "0" + strDate;
		} else {
			strDate_str = strDate;
		}
		var strHours_str
		if (strHours >= 0 && strHours <= 9) {
			strHours_str = "0" + month;
		} else {
			strHours_str = strHours;
		}
		var strMinutes_str
		if (strMinutes >= 0 && strMinutes <= 9) {
			strMinutes_str = "0" + strMinutes;
		} else {
			strMinutes_str = strMinutes;
		}
		var strSeconds_str
		if (strSeconds >= 0 && strSeconds <= 9) {
			strSeconds_str = "0" + strSeconds;
		} else {
			strSeconds_str = strSeconds;
		}
		//     if (strDate >= 0 && strDate <= 9) {
		//         strDate = "0" + strDate;
		//     }
		//     if (strHours >= 0 && strHours <= 9) {
		//         strHours = "0" + strHours;
		//     }
		//     if (strMinutes >= 0 && strMinutes <= 9) {
		//         strMinutes = "0" + strMinutes;
		//     }
		//     if (strSeconds >= 0 && strSeconds <= 9) {
		//         strSeconds = "0" + strSeconds;
		//     }
		//     
		var currentdate = date.getFullYear() + seperator1 + month_str + seperator1 + strDate_str
			+ " " + strHours_str + seperator2 + strMinutes_str
			+ seperator2 + strSeconds_str;
		return currentdate;
	}
	del_car(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("projectCar/deleteById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	//取消弹窗
	projectCarClose(modal) {
		if (this.formType == 'role') {
			$('#projectCarModal').modal("hide");
		} else {
			modal.hide();
		}

		this.projectCarFrom.installFactoryName = '';
		this.projectCarFrom.installFactoryId = '';
		this.projectCarFrom.dockingFactoryName = '';
		this.projectCarFrom.dockingFactoryId = '';
		this.projectCarFrom.deviceId = '';
		this.projectCarFrom.carNumber = '';
		this.projectCarFrom.id = '';
		this.projectCarFrom.dockingTime = this.getNowFormatDate();
		$("#dockingTime").val(this.getNowFormatDate());
		this.dockingRole = '';
	}
	//提交更新
	projectCarSubmit(modal) {
		if (this.formType == 'role') {  // 项目开启
			if (!this.dockingRole) {
				this.jsonApiService.message('请选择对接角色');
				return
			}
			let reqData = {
				roleIds: this.dockingRole,
				deviceId: this.projectCarFrom.deviceId,
				carNumber: this.projectCarFrom.carNumber,
				// companyName: this.projectCarFrom.installFactoryName,
				// companyId: this.projectCarFrom.installFactoryId,
			}
			this.jsonApiService.http_obj('projectDocking/distributionCarToRole.html', reqData).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					this.projectCarClose(modal);
				}
			});
		}
		this.projectCarFrom.dockingTime = $('#dockingTime').val();
		// TODO增加是否重置服务到期时间续费次数
		this.projectCarFrom.synRenew = this.isResetSelected ? "1" : "0";
		$('#projectCarFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#projectCarFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			let url;
			if (this.formType == 'new') { // 项目新增
				let reqData = {
					roleIds: this.dockingRole,
					deviceId: this.projectCarFrom.deviceId,
					carNumber: this.projectCarFrom.carNumber,
					// companyName: this.projectCarFrom.installFactoryName,
					// companyId: this.projectCarFrom.installFactoryId,
				}
				if (this.dockingRole) {
					this.jsonApiService.http_obj('projectDocking/distributionCarToRole.html', reqData).subscribe(data => { });
				}
				this.jsonApiService.http_obj("projectCar/add.html", this.projectCarFrom).subscribe(data => {
					this.jsonApiService.message(data.message);
					if (data.success) {
						this.load();
						this.projectCarClose(modal);
					}
				})
			} else if (this.formType == 'updata') {
				this.jsonApiService.http_obj("projectCar/update.html", this.projectCarFrom).subscribe(data => {
					this.jsonApiService.message(data.message);
					if (data.success) {
						this.load();
						this.projectCarClose(modal);
					}
				})
			}
		}
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) { return state.text };
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}

	// 查看传感器到期保修时间
	sensorTableData: any[] = []
	seeSensorNumber(row, modal) {
		this.sensorTableData = row.sensorRepairInfoList
		modal.show()
	}
	cancelSensorModal(modal) {
		this.sensorTableData = []
		modal.hide()
	}

	//查看详情
	see_details(row, modal) {
		modal.show();
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: row.deviceId
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("car/list.html", reqdata).subscribe(data => {
			if (data.isSuccess) {
				for (let item of data.exhibitDatas) {
					item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
					item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
					item.isShared = item.isShared == '1' ? true : false;
					item.picture = item.icoPath && config.BaseURL + item.icoPath.substring(1, item.icoPath.length);
				}
				this.detailsFrom = data.exhibitDatas[0];
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//详情关闭
	detailsClose(modal) {
		modal.hide()
	}
	getUseTypeNameL1(key) {
		if (key) {
			return this.carUseList[key];
		} else {
			return '';
		}
	}
	getUseTypeNameL2(key) {
		if (key) {
			return this.carDeatailUseList[key];
		} else {
			return '';
		}
	}
	// 新增或者编辑公司选中回调
	addCompanySelected1(data) {
		this.projectCarFrom.installFactoryId = data.companyId || '';
		this.projectCarFrom.installFactoryName = data.companyName;
		// 安装公司
		this.queryCarListByCompanyId(this.projectCarFrom.installFactoryId)
	}
	//新增或者编辑公司选中回调
	addCompanySelected2(data) {
		this.projectCarFrom.dockingFactoryId = data.companyId || '';
		this.projectCarFrom.dockingFactoryName = data.companyName;
		if (this.formType != 'updata') {
			this.getRoleBycompanyConfig(data.companyId);
		}
		if (this.projectCarFrom.deviceId && this.projectCarFrom.dockingFactoryId) {
			this.checkValue('1')
		}
	}
	// 根据公司拉取车辆
	queryCarListByCompanyId(companyId) {
		if (!companyId) {
			this.clearSelect2($("#carNumberSelect2"));
			this.initCar()
		} else {
			this.projectCarFrom.deviceId = '';
			this.projectCarFrom.carNumber = '';
			let reqdata = 'companyId=' + companyId;
			this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
				var carlist = data.data;
				var selectdata = [];
				for (var i = 0; i < carlist.length; i++) {
					var obj = {
						id: carlist[i].deviceId,
						text: carlist[i].carNumber,
					}
					selectdata[i] = obj;
				}
				var selectObj = $("#carNumberSelect2");
				selectObj.empty();
				this.clearSelect2(selectObj); //清除Select中的数据
				selectObj.select2({
					language: "zh-CN",
					data: selectdata, //为Select添加数据
					templateResult: this.formatRepo
				});
			})
		}
		$('#carNumberInput').val("").change();
	}
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//初始化车辆
	initCar() {
		var that = this;
		$("#carNumberSelect2").select2({
			language: "zh-CN",
			minimumInputLength: 2,
			allowClear: true,
			placeholder: "请选择",
			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 100,
				method: "POST",
				xhrFields: { withCredentials: true },
				data: function (params) { return { "carNumber": params.term }; },
				processResults: function (data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if (data.data.length <= 10) {
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if (arr.indexOf(car.carNumber) != -1) {
								sameCar.push(car.carNumber)
							} else {
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function (index, car) {
							if (sameCar.indexOf(car.carNumber) != -1) {
								options.push({
									id: car.deviceId,
									text: car.carNumber + "[" + car.parentName + "]"
								})
							} else {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					} else {
						$(data.data).each(function (index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: function (state) {
				if (!state.id) { return state.text; }
				var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
				return $state;
			},
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.projectCarFrom.deviceId = data.id;
			if (data.text.indexOf('[') > 0) {
				that.projectCarFrom.carNumber = data.text.split('[')[0];
			} else {
				that.projectCarFrom.carNumber = data.text;
			}
			if (!data.id) {
				$("#carNumberInput").val("").change();
			} else {
				$("#carNumberInput").val(that.projectCarFrom.carNumber).change();
			}
			if (that.projectCarFrom.dockingFactoryId) {
				that.checkValue('2')
			}
		});

	}
	tips() {
		// 过期信息提示
		$('.table').delegate('.fa-exclamation-circle', 'mouseenter', function (e) {
			let leftWidht = $(".fa-exclamation-circle").offset().left
			if (leftWidht > 620) {
				e.target.childNodes[1].style.left = "-600px"
			}
			if (e.target.childNodes[1] instanceof Node) {
				e.target.childNodes[1].style.display = "block"
			}
		});
		$('.table').delegate('.fa-exclamation-circle', 'mouseleave', function (e) {
			if (e.target.className == "carInfo") {
				e.target.style.display = "none"
			} else if (e.target.childNodes[1] && e.target.childNodes[1] instanceof Node) {
				e.target.childNodes[1].style.display = "none"
			}
		});
	}
	//导出
	exportData() {
		//当缴费次数有值的时候 对接厂区也必须有值存在
		if (this.renewCount.trim() && !this.selectedCompanyId2) {
			this.jsonApiService.message('请选择对接厂区');
			return
		}

		this.searchKey = common.stringTrim(this.searchKey);
		var parameters = {
			searchKey: this.searchKey,
			status: this.status,
			deviceId: this.deviceId,
			carNumber: this.carNumber,
			useTypeL1: this.useTypeL1,
			useTypeL2: this.useTypeL2,
			type: this.type,
			installFactoryId: this.selectedCompanyId,
			installFactoryName: this.selectedCompanyName,
			dockingFactoryId: this.selectedCompanyId2,
			dockingFactoryName: this.selectedCompanyName2,
			remaining: this.restDay.trim(),
			renewCount: this.renewCount.trim(),
			dockingStatus: this.dockingStatus, // 停用启用状态查询
			dateType: this.dateType,// 时间区间的类型
			startTime: this.startTime, // 开始时间
			endTime: this.endTime,  // 结束时间
			renewalDueTimeSort: this.renewalDueTimeSort, //排序类型
			isEquals: this.isEquals,
			businessType: this.businessType // 行业类型
		}
		let timeCheck = common.correctTime(parameters, ['status', 'dateType', 'useTypeL1', 'useTypeL2', 'type', 'renewalDueTimeSort'])
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'projectCar/exportProjectCarListFile.html')
	}
	//初始化车辆
	initCarNumbel() {
		var that = this;
		$("#carNumberSelect").select2({
			language: "zh-CN",
			minimumInputLength: 2,
			allowClear: true,
			placeholder: "请选择",
			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: { withCredentials: true },
				data: function (params) { return { "carNumber": params.term }; },
				processResults: function (data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if (data.data.length <= 10) {
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if (arr.indexOf(car.carNumber) != -1) {
								sameCar.push(car.carNumber)
							} else {
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function (index, car) {
							if (sameCar.indexOf(car.carNumber) != -1) {
								options.push({
									id: car.deviceId,
									text: car.carNumber + "[" + car.parentName + "]"
								})
							} else {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					} else {
						$(data.data).each(function (index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: function (state) {
				if (!state.id) { return state.text; }
				var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
				return $state;
			},
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.deviceId = data.id;
			if (data.text.indexOf('[') > 0) {
				that.carNumber = data.text.split('[')[0];
			} else {
				that.carNumber = data.text;
			}
		});

	}
	//清除车辆选中值
	del_carNumber() {
		this.deviceId = '';
		this.carNumber = '';
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect').val("");
		$("#select2-carNumberSelect-container").empty();
		$("#select2-carNumberSelect-container").attr("title", "");
		$("#select2-carNumberSelect-container").prepend(str);
	}
	//清除车辆选中值
	del_carNumber2() {
		this.projectCarFrom.deviceId = '';
		this.projectCarFrom.carNumber = '';
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberInput').val("").change();
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title", "");
		$("#select2-carNumberSelect2-container").prepend(str);
	}
	//校验重复
	checkValue(type) {
		var dataSource;
		var that = this;
		if (that.formType == 'new') {
			dataSource = {
				deviceId: that.projectCarFrom.deviceId,
				dockingFactoryId: that.projectCarFrom.dockingFactoryId
			}
		} else {
			dataSource = {
				id: that.projectCarFrom.id,
				deviceId: that.projectCarFrom.deviceId,
				dockingFactoryId: that.projectCarFrom.dockingFactoryId
			}
		}
		if (that.projectCarFrom.deviceId && that.projectCarFrom.dockingFactoryId) {
			that.jsonApiService.http_obj("projectCar/validate.html", dataSource).subscribe(data => {
				if (data.valid == false) {
					that.jsonApiService.message(data.message);
					setTimeout(function () {
						if (type == '1') {
							that.projectCarFrom.dockingFactoryName = '';
							that.projectCarFrom.dockingFactoryId = '';
						} else {
							that.projectCarFrom.carNumber = '';
							that.projectCarFrom.deviceId = '';
							that.del_carNumber2();
						}
					}, 100)
				}
			})
		}
	}
	//初始化日期插件
	initDate() {
		common.initDatePicker("#dockingTime", 0);
		$('#dockingTime').datetimepicker().on("changeDate", function (e) {
			$('#dockingTime').val(e.date).change();
		})
	}
	//初始化开关
	initSwitch() {
		var that = this;
		$('.isStatus').bootstrapSwitch({    //初始化按钮
			onText: "开启",
			offText: "停用",
			onColor: "primary",
			offColor: "warning",
			onSwitchChange: function (event, state) {
				if (state == true) {
					that.updata_car(event.target.id, 'role', '')
					that.checkStatus('0', event.target.id);
				} else {
					that.checkStatus('1', event.target.id);
				}
			}
		});
	}
	//是否启用
	checkStatus(check, id) {
		var dataSource = {
			id: id,
			status: check
		}
		this.jsonApiService.http_obj("projectCar/stopProjectCar.html", dataSource).subscribe(data => {
			if (data.success) {
				this.load()
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//设置提醒时间
	setupTime(modal) {
		this.remaining = this.remainingDay;
		modal.show();
	}
	//关闭弹窗
	setupTimeClose(modal) {
		modal.hide()
	}
	//确定
	setupTimeSubmit(modal) {
		let reqData = "remaining=" + this.remaining;
		this.jsonApiService.http("projectCar/remaining.html", reqData).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.load();
				this.setupTimeClose(modal);
			}
		})
	}

	remaining: number = 0; // 剩余天数输入框
	// 数量加
	addNum() {
		if (!Number(this.remaining)) {
			this.remaining = 1
		} else {
			this.remaining = Number(this.remaining) + 1;
		}
	}
	// 数量减
	reduceNum() {
		if (this.remaining <= 1 || !Number(this.remaining)) {
			this.remaining = 1
		} else {
			this.remaining = Number(this.remaining) - 1;
		}
	}
	// 同步项目车辆
	//打开弹窗
	openSyncCarModal(modal) {
		this.syncCompanyId = ""
		this.syncCompanyName = "";
		$("#syncCarFrom").data("bootstrapValidator").resetForm();
		modal.show();
	}
	// 关闭弹窗
	syncCarClose(modal) {
		$("#syncCarFrom").data("bootstrapValidator").resetForm();
		modal.hide();
	}
	// 选择公司的回调
	syncCompanySelect(data) {
		this.syncCompanyId = data.companyId;
		this.syncCompanyName = data.companyName;
	}
	// 提交要同步的公司
	submitSyncCar(modal) {
		$('#syncCarFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#syncCarFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			let reqdata = "companyId=" + this.syncCompanyId;
			this.jsonApiService.http('projectCar/synCarByCompanyId.html', reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
				this.syncCarClose(modal);
			})
		}
	}

	pieChart: any;
	notExpired: any = []  //总未到期
	beExpired: any = []  //总已到期数
	expiring: any = []   //总即将到期数
	expiredInMonth: any = [] //当月已到期数、
	expiringInMonth: any = [] //当月即将到期数
	colorList: any = ['#5de2ca', '#cc0000', '#ff993e', '#3333ff']
	//数据统计
	totalNumberError: any;
	beExpiredError: any;
	expiringError: any;
	expiredInMonthError: any;
	expiringInMonthError: any;
	dataModalhide(modal) {
		modal.hide();
	}
	//统计项目
	Statistics(modal) {
		var that = this;
		if (!this.selectedCompanyId2) {
			this.jsonApiService.message("请先选择对接厂区");
			return;
		}
		let reqdata = "dockingFactoryId=" + this.selectedCompanyId2;
		this.jsonApiService.http('projectCar/getTotalByCompany.html', reqdata).subscribe(data => {
			if (data.success) {
				that.beExpired = data.data.beExpired;
				that.expiring = data.data.expiring;
				that.expiredInMonth = data.data.expiredInMonth;
				that.expiringInMonth = data.data.expiringInMonth;


				let totalNumber = data.data.beExpired + data.data.expiring + data.data.expiredInMonth + data.data.expiringInMonth;
				// $('#totalNumber').text(' '+totalNumber);
				this.totalNumberError = totalNumber;
				this.beExpiredError = data.data.beExpired != 0 ? data.data.beExpired : 0;
				this.expiringError = data.data.expiring != 0 ? data.data.expiring : 0
				this.expiredInMonthError = data.data.expiredInMonth != 0 ? data.data.expiredInMonth : 0
				this.expiringInMonthError = data.data.expiringInMonth != 0 ? data.data.expiringInMonth : 0

				//			判断，没有返回值就不显示
				if (totalNumber) {
					$('.totalText').show(0);
				} else {
					$('.totalText').hide(0);
				}

				if (that.beExpired) {
					$('.beExpiredText').show(0);
				} else {
					$('.beExpiredText').hide(0);
				}

				if (that.expiring) {
					$('.expiringText').show(0);
				} else {
					$('.expiringText').hide(0);
				}

				if (that.expiredInMonth) {
					$('.expiredInMonthText').show(0);
				} else {
					$('.expiredInMonthText').hide(0);
				}

				if (that.expiringInMonth) {
					$('.expiringInMonthText').show(0);
				} else {
					$('.expiringInMonthText').hide(0);
				}

				this.loadPieChart();
				modal.show();
			}
		})
	}

	loadPieChart() {
		var that = this;
		this.pieChart = echarts.init(document.getElementById('pieChart'));
		window.onresize = function () {
			setTimeout(() => {
				that.pieChart.resize()
			}, 120)
		}
		// $(window).resize(this.pieChart.resize);
		var option = {
			color: this.colorList,
			title: {
				//text: '区间汇总统计',
				left: 'center',
				top: 20
			},
			tooltip: {
				formatter: '{b} : {c} ({d}%)'
			},
			//	    legend: {
			//	        bottom: 10,
			//	        left: 'center',
			//	        data: ['正常卸货', '异常卸货', '未配置围栏', '设备异常'],
			//	    },
			grid: {
				top: 30,
				left: 20
			},
			series: [
				{
					type: 'pie',
					radius: '45%',
					center: ['50%', '40%'],
					selectedMode: 'single',
					tilt: 0.8,
					stroke: {
						color: '#fff',
						width: 2
					},
					itemStyle: { //图形样式
						normal: {
							borderColor: '#ffffff',
							borderWidth: 2,
						},
					},
					label: {
						normal: {
							formatter: '{b}\n{d}%'
						},
					},
					data: [
						{ value: this.beExpired, name: '总已到期数' },
						{ value: this.expiring, name: '总即将到期数' },
						{ value: this.expiredInMonth, name: '当月已到期数' },
						{ value: this.expiringInMonth, name: '当月即将到期数' },
					],
					emphasis: {
						itemStyle: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
			]
		};

		this.pieChart.setOption(option);
	}


	//批量更新时间
	timeType: any = '2';
	updateTime: any = '';
	isUseInstallTime: boolean = true;  //使用安装时间同步
	batchDate(modal) {
		if (!this.selectedCompanyId2 && !this.selectedCompanyId) {
			this.jsonApiService.message("请先选择对接厂区或者安装厂区");
			return;
		}
		$("#updateTime").val('');
		this.updateTime = '';
		this.timeType = '2';
		modal.show();
		this.initUpdateTime();
	}
	batchDateModalhide(modal) {
		modal.hide();
	}
	clickTimeType(value) {
		$("#updateTime").val('');
		this.updateTime = '';
		this.timeType = value;
	}
	//初始化时间
	initUpdateTime() {
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#updateTime").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:mm:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.updateTime = time;
						$("#updateTime").val(time);//当前时间
					});
					resolve();
				});
			}
			);
		})
	}
	isUseInstallTimeChange(event) {
		this.isUseInstallTime = event.target.checked;
	}
	batchDateSubmit(modal) {
		var that = this;
		if (!$('#updateTime').val()) {
			if (this.timeType == '1' && !this.isUseInstallTime) {
				that.jsonApiService.message("请选择对接时间");
				return
			} else if (this.timeType == '2') {
				that.jsonApiService.message("请选择服务到期时间");
				return
			}
		}
		let data = {
			parameters: {
				searchKey: that.searchKey,
				status: that.status,
				deviceId: that.deviceId,
				carNumber: that.carNumber,
				installFactoryId: that.selectedCompanyId,
				installFactoryName: that.selectedCompanyName,
				dockingFactoryId: that.selectedCompanyId2,
				dockingFactoryName: that.selectedCompanyName2,
				remaining: that.restDay.trim(),
				dockingStatus: this.dockingStatus, // 停用启用状态查询
				dateType: this.dateType,// 时间区间的类型
				startTime: this.startTime, // 开始时间
				endTime: this.endTime,  // 结束时间
				renewalDueTimeSort: this.renewalDueTimeSort, //排序类型
				isEquals: this.isEquals, //厂区是否相同
				timeType: this.timeType,
				updateTime: $('#updateTime').val(),
				isUseInstallTime: this.isUseInstallTime ? '1' : ''
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		that.jsonApiService.http("projectCar/batchUpdateDate.html", reqdata).subscribe(data => {
			that.jsonApiService.message(data.message);
			modal.hide();
			that.load();
		})

	}

	// 打开取消服务到期提醒的公司的名称
	cancelBatchDate(modal) {
		//打开弹窗
		this.cancelCompanyId = ""
		this.cancelCompanyName = ""
		$("#cancelDateCompanyFrom").data("bootstrapValidator").resetForm();
		modal.show();
	}
	// 关闭弹窗
	cancelCarClose(modal) {
		$("#cancelDateCompanyFrom").data("bootstrapValidator").resetForm();
		modal.hide();
	}
	// 选择公司的回调
	cancelCompanySelect(data) {
		this.cancelCompanyId = data.companyId;
		this.cancelCompanyName = data.companyName;
	}
	// 提交要取消服务到期提醒的公司
	submitCancelDateCompany(modal) {
		$('#cancelDateCompanyFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#cancelDateCompanyFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			let reqdata = "companyId=" + this.cancelCompanyId;
			this.jsonApiService.http('projectCar/cancelReminder.html', reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
				this.cancelCarClose(modal);
			})
		}
	}


	// 打开取消服务到期提醒的公司的名称
	resetBatchDate(modal) {
		//打开弹窗
		this.resetCompanyId = ""
		this.resetCompanyName = ""
		this.companySeverRemind = '1'
		$("#resetDateCompanyFrom").data("bootstrapValidator").resetForm();
		modal.show();
	}
	// 关闭弹窗
	resetCompanyClose(modal) {
		$("#resetDateCompanyFrom").data("bootstrapValidator").resetForm();
		modal.hide();
	}
	// 选择公司的回调
	resetCompanySelect(data) {
		this.resetCompanyId = data.companyId;
		this.resetCompanyName = data.companyName;
	}
	// 提交要重置服务到期的公司
	submitResetDateCompany(modal) {
		$('#resetDateCompanyFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#resetDateCompanyFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			let reqdata = "companyId=" + this.resetCompanyId + '&type=' + this.companySeverRemind;
			this.jsonApiService.http('projectCar/batchSync.html', reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
				this.resetCompanyClose(modal);
			})
		}
	}

	//查看续费详情
	see_renewDetails(row, modal) {
		modal.show();
		let reqdata = {
			billType : row.dockingFactoryId===row.installFactoryId ? 1 : 2,
			dockingFactoryId: row.dockingFactoryId,
			deviceId: row.deviceId
		}
		// let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http_obj("renewal/getRenewalInfo.html", reqdata).subscribe(data => {
			if (data.success) {
				this.renewDetailsTable = data.data;
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//详情关闭
	renewDetailsClose(modal) {
		modal.hide()
	}

	resetSelectClick() {
		this.isResetSelected = !this.isResetSelected;
	}



	//对接角色
	userList: any = [];
	// 根据对接厂区拉取配饰对接的角色数据
	getRoleBycompanyConfig(companyId) {
		var that = this;
		that.userList = [];
		that.jsonApiService.http_obj("projectDocking/getRoleInfoByCompany.html", { companyId: companyId }).subscribe(data => {
			if (data.success) {
				var userList = data.data;
				var selectdata = [];
				if (userList.length == 0) {
					this.RoleXxplain = '对接厂区没有配置对接角色,请先配置项目对接角色';
					that.jsonApiService.message('对接厂区没有配置对接角色,请先配置项目对接角色');
				} else {
					for (var i = 0; i < userList.length; i++) {
						var obj = {
							id: userList[i].roleId,
							text: userList[i].roleName,
							check: false
						}
						selectdata[i] = obj;
					}
					that.userList = selectdata;
					//数据为一个时候 默认选中
					if (that.userList.length == 1) {
						that.userList[0].check = true;
						this.dockingRole = that.userList[0].id
					}
				}

			}
		})
	}
	checkBoxRole(value, id) {
		var userData = []
		for (var i = 0; i < this.userList.length; i++) {
			if (this.userList[i].id == id) {
				if (value.checked) {
					this.userList[i].check = true
				} else {
					this.userList[i].check = false
				}
			}
		}

		for (var j = 0; j < this.userList.length; j++) {
			if (this.userList[j].check) {
				userData.push(this.userList[j].id)
			}
		}

		this.dockingRole = userData.join(',');
		$("#projectCarFrom").data('bootstrapValidator').resetForm();
		console.log(this.dockingRole)
	}

	// 路由跳转
	jumpToPage(e, url) {
		$('#projectCarModal').modal('hide');
		e.stopPropagation();
		this.router.navigate([url]);
	}

	/**
	 * 修改保修到期时间
	 */
	maintenanceDateForm: any = {
		deviceId: '',
		carNumber: '',
		warrantyExpirationTime: '',  //主机保修到期时间
		sensorRepairInfoList: [] //传感器
	}
	maintenanceDate(modal) {
		modal.show()
		this.initMaintenanceCar()
		this.del_maintenanceCarNumber()
	}
	maintenanceDateModalhide(modal) {
		this.del_maintenanceCarNumber()
		modal.hide()
	}
	//清除车辆选中值
	del_maintenanceCarNumber() {
		this.maintenanceDateForm.deviceId = '';
		this.maintenanceDateForm.carNumber = '';
		this.maintenanceDateForm.warrantyExpirationTime = '';
		this.maintenanceDateForm.sensorRepairInfoList = [];
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#maintenanceCarNumber').val("");
		$("#select2-maintenanceCarNumber-container").empty();
		$("#select2-maintenanceCarNumber-container").attr("title", "");
		$("#select2-maintenanceCarNumber-container").prepend(str);
	}
	//初始化车辆
	initMaintenanceCar() {
		var that = this;
		$("#maintenanceCarNumber").select2({
			language: "zh-CN",
			minimumInputLength: 2,
			allowClear: true,
			placeholder: "请选择",
			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 100,
				method: "POST",
				xhrFields: { withCredentials: true },
				data: function (params) { return { "carNumber": params.term }; },
				processResults: function (data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if (data.data.length <= 10) {
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if (arr.indexOf(car.carNumber) != -1) {
								sameCar.push(car.carNumber)
							} else {
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function (index, car) {
							if (sameCar.indexOf(car.carNumber) != -1) {
								options.push({
									id: car.deviceId,
									text: car.carNumber + "[" + car.parentName + "]"
								})
							} else {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					} else {
						$(data.data).each(function (index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: function (state) {
				if (!state.id) { return state.text; }
				var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
				return $state;
			},
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.maintenanceDateForm.deviceId = data.id;
			if (data.text.indexOf('[') > 0) {
				that.maintenanceDateForm.carNumber = data.text.split('[')[0];
			} else {
				that.maintenanceDateForm.carNumber = data.text;
			}
			if (!data.id) {
				$("#maintenanceCarNumberInput").val("").change();
			} else {
				$("#maintenanceCarNumberInput").val(that.projectCarFrom.carNumber).change();
				that.searchList()
			}
		});
	}
	//查询列表 有几个传感器
	searchList() {
		const that = this
		let data = {
			pageSize: 10,
			nowPage: 1,
			parameters: {
				deviceId: that.maintenanceDateForm.deviceId,
				carNumber: that.maintenanceDateForm.carNumber
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		that.jsonApiService.http("projectCar/list.html", reqdata).subscribe(data => {
			if (data.isSuccess) {
				if (data.exhibitDatas.length && data.exhibitDatas.length > 0) {
					that.maintenanceDateForm.warrantyExpirationTime = data.exhibitDatas[0].warrantyExpirationTime
					that.maintenanceDateForm.sensorRepairInfoList = data.exhibitDatas[0].sensorRepairInfoList
					this.initMaintenanceTime() //更新时间
				}
			} else {
				that.jsonApiService.message(data.message);
			}
		})
	}
	//初始化时间
	initMaintenanceTime() {
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					let timer = setTimeout(() => {
						$("#warrantyExpirationTime").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:mm:ss",
							language: "zh-CN",
							autoclose: true,
						}).on("changeDate", function (e) {
							var date = e.date;
							var time = common.getTimeMmss(date);
							that.maintenanceDateForm.warrantyExpirationTime = time;
							$("#warrantyExpirationTime").val(time);//当前时间
						});
						//可能存在多个传感器情况
						if (that.maintenanceDateForm.sensorRepairInfoList.length > 0) {
							for (let i = 0; i < that.maintenanceDateForm.sensorRepairInfoList.length; i++) {
								console.log($("#warrantyExpirationTime" + i), '000000000')
								$("#warrantyExpirationTime" + i).datetimepicker({//时间插件
									format: "yyyy-mm-dd hh:mm:ss",
									language: "zh-CN",
									autoclose: true,
								}).on("changeDate", function (e) {
									var date = e.date;
									var time = common.getTimeMmss(date);
									that.maintenanceDateForm.sensorRepairInfoList[i].warrantyExpirationTime = time;
									$("#warrantyExpirationTime" + i).val(time);//当前时间
								});
							}
						}
						clearTimeout(timer)
						timer = null
						resolve();
					}, 500)
				});
			}
			);
		})
	}
	maintenanceDateSubmit(modal) {
		let formValue = {
			deviceId: this.maintenanceDateForm.deviceId,
			carNumber: this.maintenanceDateForm.carNumber,
			warrantyExpirationTime: this.maintenanceDateForm.warrantyExpirationTime,  //主机保修到期时间
			sensorRepairInfoListStr: '' //传感器列表
		}
		let list = JSON.parse(JSON.stringify(this.maintenanceDateForm.sensorRepairInfoList))
		if (!formValue.deviceId) {
			this.jsonApiService.message('请先选择车牌号')
			return
		}
		if (!formValue.warrantyExpirationTime) {
			this.jsonApiService.message('请先选择主机保修到期')
			return
		}
		if (list.length > 0) {
			for (let i = 0; i < list.length; i++) {
				if (!list[i].warrantyExpirationTime) {
					this.jsonApiService.message('请先选择传感器' + list[i].sensorNumber + '保修到期')
					return
				} else {
					delete list[i].updateDate
					delete list[i].updateUser
				}
			}
		}
		formValue.sensorRepairInfoListStr = JSON.stringify(list)
		let reqdata = JSON.parse(JSON.stringify(formValue))
		this.jsonApiService.http_obj('projectCar/updateWarrantyExpirationTime.html', reqdata).subscribe(data => {
			this.jsonApiService.message(data.message)
			if (data.success) {
				this.maintenanceDateModalhide(modal)
				this.load() //重新请求页面
			}
		})

	}

	//行业类型选择
	businessTypeChange(e) {
		this.businessType = e
	}
}